package uit.edu.vn.Utility;

import java.io.FileInputStream;
import java.net.URL;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;

import android.util.Log;



public class httpUploader {
	
    URL connectURL;
	String responseString;
	String t= "";
	String fileName;
	String username ;
	byte[ ] dataToServer;
	FileInputStream fileInputStream = null;
	
	public httpUploader(String urlString, String user, String Name ){
        try{
                connectURL = new URL(urlString);
        }catch(Exception ex){
                Log.i("URL FORMATION","MALFORMATED URL");
        }
        username = user;
        fileName = Name;
	}
	
    public String doStart(FileInputStream stream){
        fileInputStream = stream;
        return thirdTry();
    }
    
    
    public String thirdTry(){
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag="3rd";
        String respose = "";
        try
        {
                //------------------ CLIENT REQUEST

                Log.e(Tag,"Starting to bad things");
                
                // Open a HTTP connection to the URL
                HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");

                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                t +=twoHyphens + boundary + lineEnd;
//                dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName +"\"" + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\""+username+"\";filename=\"" + fileName +"\"" + lineEnd);
                
                t += "Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName +"\"" + lineEnd;
                dos.writeBytes(lineEnd);
                t += lineEnd;
                //toi buoc nay thi da dua duoc du lieu vao luong DataOutputStream chua???
                Log.e(Tag,"Headers are written");

                //----------create a buffer of maximum size----------
                
                
                int bytesAvailable = fileInputStream.available();//doc so bytes cua file dinh gui
                int maxBufferSize = 1024;
                //lay buffersize nho nhat giua 2 gia tri 1024 va tong so byte cua file
                int bufferSize = Math.min(bytesAvailable, maxBufferSize);
                //tao array  buffer voi bufferSize
                byte[ ] buffer = new byte[bufferSize];

                // read file and write it into form...
                //doc file len tu luong FileInputStream, tu byte 0 den bufferSize
                int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                //tao vong lap de gui file len theo tung bufferSize
                while (bytesRead > 0)
                {
                            //ghi so byte doc len dc va luong dataoutputstream thong qua array buffer
                        dos.write(buffer, 0, bufferSize);
                        //lay lai so byte hien tai con lai
                        bytesAvailable = fileInputStream.available();
                        //dat lai gia tri cua bufferSize de den khi doc den nhung byte
                        //cuoi cung cua file thi so byte con lai co the nho hon 1024
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        //doc bufferSize byte tu file
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }
                t += "writing data...";
                // send multipart form data necesssary after file data...
                
                dos.writeBytes(lineEnd);
                t += lineEnd;
                //chuoi bao hieu hoan tat tien trinh upload file
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                t += twoHyphens + boundary + twoHyphens + lineEnd;
                System.out.println("xxxxxxxxxxxx:   \n"+ t);
                
                // close streams
                Log.e(Tag,"File is written");
                fileInputStream.close();
                dos.flush();

                InputStream is = conn.getInputStream();
                // retrieve the response from server
                //Nhan chuoi thong bao thanh cong hoac that bai tu Server gui ve
                int ch;
                StringBuffer b =new StringBuffer();
                while( ( ch = is.read() ) != -1 ){
                        b.append( (char)ch );
                }
                respose=b.toString();
                System.out.println("String response is: " +respose);
                Log.i("Response",respose);
                dos.close();

        }
        catch (MalformedURLException ex)
        {
                Log.e(Tag, "error URL: " + ex.getMessage(), ex);
        }

        catch (IOException ioe)
        {
                Log.e(Tag, "error IO: " + ioe.getMessage(), ioe);
        }
		return respose;
        
}



}
